package cn.itsource.ymcc.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.domain.SmsCodeVo;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICommonService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.StrUtils;
import com.google.errorprone.annotations.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public JsonResult imageCode(String imageCodeKey) {
        //生成图片验证和验证码
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(300, 100, 4, 4);
        //得到验证码
        String code = shearCaptcha.getCode();
        String imageBase64 = shearCaptcha.getImageBase64();//base64的图片  没有前缀
        //保存redis
        redisTemplate.opsForValue().set(imageCodeKey,code,6, TimeUnit.MINUTES);
        return JsonResult.success().setData(imageBase64);
    }

    @Override
    public JsonResult sendSmsCode(SmsCodeVo smsCodeVo) {
        String imageCodeKey = smsCodeVo.getImageCodeKey() + Constants.REGISTER;
        //校验图片验证码
        AssertUtil.isTrue(redisTemplate.hasKey(imageCodeKey),"图片验证码已过期");//判断redis里面有没有这个key
        String imageCode = smsCodeVo.getImageCode();//用户输入的
        boolean blean = imageCode.equalsIgnoreCase(redisTemplate.opsForValue().get(imageCodeKey).toString());
        AssertUtil.isTrue(blean,"图片验证码错误");//equalsIgnoreCase忽略大小写


        //生成code  新的
        String smsCodeValue = StrUtils.getRandomString(6);
        String smsCodekey = smsCodeVo.getMobile()+Constants.REGISTER;
        //规则  3分钟使用同一个  1分钟重发
        if(redisTemplate.hasKey(smsCodekey)){
            //ttl redis 返回当前key的剩余时间   :
            Long seconds = redisTemplate.getExpire(smsCodekey, TimeUnit.SECONDS);//获取当前key的剩余时间
            if(seconds>240){
                JsonResult.error("打手");
            }
            if(seconds>120){//小于三分钟
                smsCodeValue = redisTemplate.opsForValue().get(smsCodekey).toString();
            }
        }
        //设置短信验证码到redis
        redisTemplate.opsForValue().set(smsCodekey,smsCodeValue,5,TimeUnit.MINUTES);
        //短信 邮箱
        System.out.println(smsCodeValue);
        return JsonResult.success();
    }
}
